from textual.screen import ModalScreen
from textual.widgets import Button, Input
from textual.containers import Grid
from mywidgets.file_edit_table import FileEditTable
from rich.text import Text
from textual import on


class FileEditScreen(ModalScreen[bool]):  # 设置界面
    CSS = """
        Input:focus {
            border: tall orange;
        }
    """
    def __init__(self, file_name) -> None:  # file_name = file_path
        super().__init__() 
        self.file_name = file_name
        
    def key_up(self):
        self.query_one("#file_edit_table").action_cursor_up()

    def key_down(self):
        self.query_one("#file_edit_table").action_cursor_down()
    
    def key_shift_left(self):
        self.query_one("#file_edit_table").scroll_left()

    def key_shift_right(self):
        self.query_one("#file_edit_table").scroll_right()

    def key_backspace(self):
        if self.query_one("#file_edit_input").has_focus:
            input_widget = self.query_one("#file_edit_input")
            table = self.query_one("#file_edit_table")
            # 当输入框正在被使用，光标在最前面
            if input_widget.cursor_position == 0 and table.cursor_row != 0:
                # 保存table本行内容
                this_row_content = table.get_row_at(table.cursor_row)[0]
                # table本行之后的内容依次往前覆盖一行
                for i in range(table.cursor_row, len(table.rows)-1):
                    table.update_cell_at((i,0),table.get_row_at(i+1)[0])
                # 高亮行前移
                table.action_cursor_up()
                # 将之前保存的内容追加至这一行
                table.update_cell_at((table.cursor_row,0),table.get_row_at(table.cursor_row)[0].split('\n')[0]+this_row_content)
                # 删除最后一行
                last_key, _ = table.coordinate_to_cell_key((len(table.rows)-1,0))
                table.remove_row(last_key)

    def key_enter(self):
        if self.query_one("#file_edit_input").has_focus:
            table = self.query_one("#file_edit_table")
            input_widget = self.query_one("#file_edit_input")
            # 获取高亮行内容
            init_row_content = table.get_row_at(table.cursor_row)[0]
            # 从输入框光标处分为两部分
            this_row_content = str(init_row_content[:input_widget.cursor_position])
            next_row_content = str(init_row_content[input_widget.cursor_position:])
            # 前半部分留在本行,末尾加换行符
            table.update_cell_at((table.cursor_row,0),this_row_content+'\n')
            # 末尾追加一行,行号+1
            label = Text(str(len(table.rows)+1), style="#B0FC38 italic")
            table.add_row(label=label)
            # 高亮行之后所有行，依次往后推移一行
            for i in range(len(table.rows)-1, table.cursor_row, -1):
                table.update_cell_at((i,0),table.get_row_at(i-1)[0])
            # 高亮行下行
            table.action_cursor_down()
            # 将之前的后半部分更新到这一行
            table.update_cell_at((table.cursor_row,0),next_row_content)

    def compose(self):
        yield Grid(
            FileEditTable(id="file_edit_table", file_name=self.file_name),
            Input(id="file_edit_input"),
            Button("保存", variant="success", id="file_edit_save"),
            Button("取消", variant="error", id="file_edit_quit"),
            id="file_edit_window",
        )

    @on(Input.Changed)
    def input_changed(self, event: Input.Changed) -> None:
        file_table = self.query_one("#file_edit_table")
        input_widget = self.query_one("#file_edit_input")
        input_content = input_widget.value
        file_table.update_cell_at((file_table.cursor_row, 0), input_content)

    def on_mount(self):
        self.query_one("#file_edit_input").focus()
        self.query_one("#file_edit_input").cursor_position = 0

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "file_edit_quit":
            self.dismiss(False)
        else:  # 保存
            table = self.query_one("#file_edit_table")
            content = []
            for i in range(len(table.rows)):
                content.append(str(table.get_row_at(i)[0]))
            with open(self.file_name, 'w') as f:
                f.writelines(content)
            self.dismiss(True)

